﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace UDS.Build.Database.Replication
{
    class PublicationDefinition
    {
        private Dictionary<string, PublishedTableDefinition> tables;
        private string version = String.Empty;

        public PublicationDefinition()
        {
            tables = new Dictionary<string, PublishedTableDefinition>();
        }

        public void Load(Publication pub)
        {
            foreach (PublicationPublishedTable tab in pub.PublishedTable)
            {
                PublishedTableDefinition table;
                if (tables.TryGetValue(tab.TableName, out table))
                {
                    // Ignore this if we already have newer version table.
                    if (table.Version.CompareTo(pub.Version) > 0)
                    {
                        continue;
                    }
                    else
                    {
                        // Otherwise, replace with current table.
                        tables.Remove(tab.TableName);
                    }
                }
                table = new PublishedTableDefinition(pub.Version, tab);
                tables.Add(tab.TableName, table);
            }
            if (version.CompareTo(pub.Version) < 0)
            {
                version = pub.Version;
            }
        }

        public string Version
        {
            get
            {
                return version;
            }
        }

        public IEnumerable<PublishedTableDefinition> Tables
        {
            get
            {
                return tables.Values;
            }
        }
        public void GenerateSQL(string fileName)
        {
            FileStream s = new FileStream(fileName, FileMode.Create);
            using (StreamWriter w = new StreamWriter(s))
            {
                w.WriteLine("-- Replication stored procedures for publication version {0}", version);
                foreach (PublishedTableDefinition table in tables.Values)
                {
                    SprocReplicationGenerator gen = new SprocReplicationGenerator(table, w);
                    w.Write(string.Format("\r\n----\r\n---- Replication custom procedures for article '{0}':\r\n----\r\n\r\n", table.Name));
                    gen.GetInsertSQL();
                    gen.GetUpdateSQL();
                    gen.GetDeleteSQL();
                }
            }
        }
    }
}
